// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
const Vue = require("vue/dist/vue");
const electron = require("electron");
const request = require("request")
const fs = require("fs");
const path = require("path");
new Vue({
  el: "#vueapp",
  data() {
    return {
      body : {goodsIds: ["6800948071"]},
      title:"",
      price:"",
      detaile:[],
      parse:"",
      main_img_parse: ""
    }
  },
  mounted() {
    this._layuiInit();
  },
  methods: {
    getSource(){
      request({
          method: "post",
          url: "https://youhui.pinduoduo.com/network/api/goods/queryByGoodsId",
          headers: {"Content-type": "application/json; charset=UTF-8"},
          body: JSON.stringify(this.body)        
      },(err,res,body)=>{
          let response = JSON.parse(body);
          const main_img = [response.result.goodsDetails[0].goodsImageUrl,response.result.goodsDetails[0].goodsThumbnailUrl];
          this.detaile = response.result.goodsDetails[0].goodsGalleryUrls;
          this.title = response.result.goodsDetails[0].goodsName;
          // console.log(this.title)
          let titles = this.title;
          this.title = this.title.split("/").join("")
          this.price = response.result.goodsDetails[0].minGroupPrice;
          fs.mkdir(path.join(__dirname, "数据包",this.title+"主图") ,(error)=>{
              if(error){
                  console.log(error);
                  return false;
              };
              for(let i = 0;i<main_img.length;i++){
                  request(main_img[i],()=>{
                    if(i == 1){
                      this.main_img_parse = "FILE:///"+ path.join(__dirname, "数据包",this.title+"主图" ,1+".jpg")
                    }
                  })
                  .pipe( fs.createWriteStream(path.join(__dirname, "数据包",this.title+"主图", i+".jpg")) );
              }  
          })
          fs.mkdir(path.join(__dirname, "数据包",this.title+"详情页"),(error)=>{
              if(error){
                  console.log(error);
                  return false;
              };
              for(let i = 0;i<this.detaile.length;i++){
                  request(this.detaile[i])
                  .pipe( fs.createWriteStream(path.join(__dirname, "数据包",this.title+"详情页", i+".jpg")) );
              }  
          })
          const version = "version 1.00"
          this.price = (this.price/100).toFixed(2)
          let detail = "";
          this.parse = path.join(__dirname,"数据包");
          console.log(this.main_img_parse)
          for(let i = 0;i<this.detaile.length;i++){
              detail += `<img alt="""" src=""FILE:///${path.join(__dirname,"数据包",this.title+"详情页",i+".jpg")}"" style=""width:750px;"">`
          }
          let str = {
              "title":{
                  text: "宝贝名称",
                  value:  titles
              },
              "cid":{
                  text: "宝贝类目",
                  value: ""
              },
              "seller_cids":{
                  text:  "店铺类目",
                  value: ""
              },
              "stuff_status":{
                  text: "新旧程度",
                  value: "1"
              },
              "location_state":{
                  text: "省",
                  value: ""
              },
              "location_city":{
                  text: "城市",
                  value: ""
              },
              "item_type":{
                  text: "出售方式",
                  value: "1"
              },
              "price":{
                  text: "宝贝价格",
                  value: this.price
              },
              "auction_increment":{
                  text: "加价幅度",
                  value: "0"
              },
              "num":{
                  text: "宝贝数量",
                  value: ""
              },
              "valid_thru":{
                  text: "有效期",
                  value: "7"
              },
              "freight_payer":{
                  text: "运费承担",
                  value: "0"
              },
              "post_fee":{
                  text: "运费承担",
                  value: "0"
              },
              "ems_fee":{
                  text: "EMS",
                  value: "0"
              },
              "express_fee":{
                  text: "快递",
                  value: "0"
              },
              "has_invoice":{
                  text: "发票",
                  value: "0"
              },
              "has_warranty":{
                  text: "保修",
                  value: "0"
              },
              "approve_status":{
                  text: "放入仓库",
                  value: "1"
              },
              "has_showcase":{
                  text: "橱窗推荐",
                  value: "0"
              },
              "list_time":{
                  text: "开始时间",
                  value: ""
              },
              "description":{
                  text: "宝贝描述",
                  value: `"<p><br>
          ${detail}</p>"`
              },
              "cateProps":{
                  text: "宝贝属性",
                  value: ""
              },
              "postage_id":{
                  text: "邮费模版ID",
                  value: "0"
              },
              "has_discount":{
                  text: "会员打折",
                  value: "0"
              },
              "modified":{
                  text: "修改时间",
                  value:""
              },
              "upload_fail_msg":{
                  text: "上传状态",
                  value:"0"
              },
              "picture_status":{
                  text: "图片状态",
                  value: "1;1;1;1;1;"
              },
              "auction_point":{
                  text: "返点比例",
                  value: "0"
              },
              "picture": {
                  text: "新图片",
                  value: ""
              },
              "video":{
                  text: "视频",
                  value: "0"
              },
              "skuProps":{
                  text: "销售属性组合",
                  value: ""
              },
              "inputPids":{
                  text: "用户输入ID串",
                  value: ""
              },
              "inputValues":{
                  text: "用户输入名-值对",
                  value: ""
              },
              "outer_id":{
                  text: "商家编码",
                  value:""
              },
              "propAlias":{
                  text:"销售属性别名",
                  value:""
              },
              "auto_fill":{
                  text: "代充类型",
                  value:"0"
              },
              "num_id":{
                  text: "数字ID",
                  value:""
              },
              "local_cid":{
                  text: "本地ID",
                  value: ""
              },
              "navigation_type":{
                  text: "宝贝分类",
                  value: "-1"
              },
              "user_name":{
                  text: "用户名称",
                  value: ""
              },
              "syncStatus":{
                  text: "宝贝状态",
                  value: "1"  
              },
              "is_lighting_consigment":{
                  text: "闪电发货",
                  value: "0"
              },
              "is_xinpin":{
                  text: "新品",
                  value: "0"
              },
              "foodparame":{
                  text: "食品专项",
                  value: ""
              },
              "features":{
                  text: "尺码库",
                  value: ""
              },
              "buyareatype":{
                  text: "采购地",
                  value: "国内"
              },
              "global_stock_type":{
                  text: "库存类型",
                  value: "-1"
              },
              "global_stock_country":{
                  text: "国家地区",
                  value: "中国"
              },
              "sub_stock_type":{
                  text: "库存计数",
                  value: "1"
              },
              "item_size":{
                  text: "物流体积",
                  value: ""
              },
              "item_weight":{
                  text: "物流重量",
                  value: ""
              },
              "sell_promise":{
                  text: "退换货承诺",
                  value: ""
              },
              "custom_design_flag":{
                  text: "定制工具",
                  value: "1"
              },
              "wireless_desc":{
                  text: "无线详情",
                  value: ""
              },
              "cpv_memo":{
                  text: "属性值备注",
                  value: ""
              },
              "input_custom_cpv":{
                  text: "自定义属性值",
                  value: ""
              }
          }
  
          let keys = Object.keys(str);
          console.log(str);
          const header = keys.join(",")
          let ceel = [];
          let value = []
          for(let i=0;i<keys.length;i++){
              ceel.push(str[keys[i]].text)
              value.push(str[keys[i]].value)
          }
          ceel = ceel.join(",")
          value = value.join(",")
          const csv = version + "\n" + header + "\n" + ceel + "\n" + value;
          fs.writeFile(path.join(__dirname,"数据包",`${this.title}.csv`), '\ufeff' + csv, {encoding: 'utf8'},()=>{});
          layer.closeAll('loading');
      })
    },
    _layuiInit(){
      layui.use("layer",()=>{
        this.layer = layui.layer;
      });
      // layui.use("element",()=>{
      // });
    },
    submit(e){
      e.preventDefault()
      let msg = this.$refs.input.input.value
      this.$refs.input.input.value = ""
      if(!msg){
        this.layer.msg('商品ID不能为空', {
          time: 1000, //1s后自动关闭
          area:['200px', '60px']
        });
      }else{
        this.body.goodsIds[0] = msg;
        // this.layer.load();
        this.layer.load();
        this.getSource();
      }
    }
  },
})
